﻿using App.API.BaseFilter;
using App.IBLL;
using App.Model.FileInfo;
using APP.DTO;
using APP.DTO.ApplicationInfo;
using APP.DTO.FileInfo;
using DataService.Core.Common;
using DataService.Core.Json;
using DataService.Core.Log;
using DataService.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Configuration.UserSecrets;
using Microsoft.Extensions.Options;
using System.Drawing;

namespace App.API.Controllers
{
    [Route("API/[Controller]/[Action]")]
    [ApiController]
    public class FilesController : APIControllerBase
    {
        private readonly FilePathDTO _filePathDTO;
        private IRequestResponseRecordBLL _requestResponseRecordBLL;
        public FilesController(IOptions<FilePathDTO> dtoSetting, IRequestResponseRecordBLL requestResponseRecordBLL)
        {
            _filePathDTO = dtoSetting.Value;

            _requestResponseRecordBLL = requestResponseRecordBLL;
        }

        //[HttpPost]
        //public async Task<IActionResult> DownFileByStream()
        //{
        //    string file_path = @"";
        //    using (var sw = new FileStream(file_path, FileMode.Open))
        //    {
        //        var bytes = new byte[sw.Length];
        //        sw.Read(bytes, 0, bytes.Length);
        //        sw.Close();
        //        return new FileContentResult(bytes, "image/jpeg");
        //    }
        //}
        //[HttpPost]
        //public async Task<FileResult> DownPhysicalFile()
        //{
        //    string filePath = "";//文件全路径，例：D:\A1.jpg
        //    return PhysicalFile(filePath, "image/jpeg");
        //}


        /// <summary>
        /// 批量上传附件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public HandleResult MultipleUploadFile()
        {
            HandleResult handleResult = new HandleResult { StatusCode = 200 };

            string userId = string.Empty;//需要获取请求的用户主键
            try
            {
                //1.获取参数
                Dictionary<string, string> paraDic = GetRequestForm(HttpContext.Request.Form);
                //.Net FrameWork使用此方法获取文件流
                // HttpPostedFile f1 = HttpContext.Current.Request.Files[0];
                //.Net Core使用此方法获取文件流
                IFormFileCollection files = HttpContext.Request.Form.Files;
                if (files == null | files.Count == 0)
                {
                    handleResult.StatusCode = 0;
                    handleResult.Msg = "没有需要导入的文件";
                    return handleResult;
                }
                var backUpFileDataList = new List<FileRecordInfo>();
                Snowflake snowflake = new Snowflake();
                foreach (IFormFile fileItem in files)
                {
                    Console.WriteLine(fileItem.FileName + "***" + fileItem.Name + "***" + _filePathDTO.InfomationFilePath);

                    string jsonData = paraDic[fileItem.FileName];
                    RequestUploadFileDTO requestUploadFileDTO = JsonHelper.ToJsonEntity<RequestUploadFileDTO>(jsonData);

                    FileRecordDTO createFileDTO = CreateFile(requestUploadFileDTO.FileName, fileItem);


                    long id = snowflake.NewId();

                    #region 组装备份文件数据
                    var backUpFileDataModel = GetBackUpFileData(createFileDTO, paraDic[fileItem.FileName], userId, id);
                    backUpFileDataList.Add(backUpFileDataModel);
                    #endregion
                }
                _requestResponseRecordBLL.SaveFileRecord(backUpFileDataList);

                #region 保存至数据库业务逻辑

                #endregion

            }
            catch (Exception ex)
            {
                TraceLog.WriteLine($"报错位置：{ex.StackTrace.ToString()},异常信息：{ex.Message}");

                handleResult.StatusCode = 0;
                handleResult.Msg = "保存文件异常";
            }
            return handleResult;
        }


        private Dictionary<string, string> GetRequestForm(IFormCollection formCollection)
        {
            Dictionary<string, string> paraDic = new Dictionary<string, string>();
            if (formCollection != null)
            {
                foreach (var item in formCollection.Keys)
                {
                    string formValue = formCollection[item];
                    paraDic[item] = formValue;
                }
            }
            return paraDic;
        }


        private FileRecordDTO CreateFile(string soureceFileName, IFormFile fileItem)
        {
            FileRecordDTO createFileDTO = new FileRecordDTO();

            string month = DateTime.Now.ToString("yyyyMMdd");
            string targetFilePath = Path.Combine(_filePathDTO.InfomationFilePath, month);
            targetFilePath = FilePathHelper.EnsureDirectory(targetFilePath, false);


            string extension = Path.GetExtension(soureceFileName);
            string fileName = soureceFileName.Replace(extension, "") +"_"+ DateTime.Now.ToString("yyyyMMddHHmmssfff") + extension;
            fileName = fileName.Replace(" ", "");
            string tempPath = Path.Combine(targetFilePath, fileName);
            using (Stream stream = fileItem.OpenReadStream())
            {
                using (Stream fileStream = new FileStream(tempPath, FileMode.Create))
                {
                    stream.CopyTo(fileStream);
                    fileStream.Flush();
                }
            }
            //相对路径 存到数据库
            string tempRealtionPath = "/" + month + "/" + fileName;

            var fileInfo = new FileInfo(tempPath);

            createFileDTO.AbsoluteFullPath = tempPath;
            createFileDTO.RelativeFilePath = tempRealtionPath;
            createFileDTO.ByteLength = (int)fileInfo.Length;
            createFileDTO.FullFileName = soureceFileName;

            return createFileDTO;
        }
        private FileRecordInfo GetBackUpFileData(FileRecordDTO fileParamDTO, string jsonFileData, string userId, long id)
        {
            byte[] tempBuffer = FileHelper.ReadFile(fileParamDTO.AbsoluteFullPath);
            var backUpFileDataModel = new FileRecordInfo
            {
                ID = id,
                FileBuffer = tempBuffer,
                FileName = fileParamDTO.FullFileName,
                CreateTime = DateTime.Now,
                UserId = userId,
                FileTextData = jsonFileData,
                FullFileName = fileParamDTO.AbsoluteFullPath
            };
            return backUpFileDataModel;
        }


    }
}
